
package com.wzt.lianfirecontrol.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class WebViewSettingUtils {

    /**
     * webview的通用设置
     * @param webView
     * @param context
     * @return
     */
    @SuppressLint("SetJavaScriptEnabled")
    public static WebView getSettingInstance(WebView webView,
                                             final Context context) {
        webView.setVerticalScrollBarEnabled(false);

        WebSettings settings = webView.getSettings();
        // 支持js
        settings.setJavaScriptEnabled(true);
        // 支持通过JS打开新窗口
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        // 打开页面时， 自适应屏幕
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        // 设置可以访问文件
        settings.setAllowFileAccess(true);
        settings.setDefaultTextEncodingName("UTF-8");
        // 支持dom数据存储WebStorage
        settings.setDomStorageEnabled(true);
        // 设置webview内部字体的缩放比例
        settings.setTextZoom(100);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setAppCacheEnabled(false);
        String ua = settings.getUserAgentString();
        settings.setUserAgentString(ua + "; APP_USER/lianfire");
        webView.setVerticalScrollbarOverlay(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // android 5.0之后原生webview同时用https和http加载HTML不加载图片解决方案
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            // 允许第三方写cook
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptThirdPartyCookies(webView, true);
        }

        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent,
                                        String contentDisposition, String mimetype, long contentLength) {
                // TODO Auto-generated method stub
                try {
                    Uri uri = Uri.parse(url);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    context.startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        return webView;
    }
}
